package com.focusai.efairy.ui.activity.dev;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.focusai.efairy.R;
import com.focusai.efairy.business.dev.DeviceDrawHelper;
import com.focusai.efairy.model.dev.DeviceDetailInfo;
import com.focusai.efairy.model.dev.DeviceItem;
import com.focusai.efairy.model.dev.DeviceRealTimeDataItem;
import com.focusai.efairy.model.dev.ImgAssistInfo;
import com.focusai.efairy.model.report.DevLineData;
import com.focusai.efairy.model.request.GetDeviceDetailRequest;
import com.focusai.efairy.model.response.DeviceDetailInfoResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.activity.maintain.MaintainRecordeListActivity;
import com.focusai.efairy.ui.adapter.dev.DeviceInfoCidRealViewBinder;
import com.focusai.efairy.ui.adapter.dev.DeviceInfoImgViewBinder;
import com.focusai.efairy.ui.adapter.dev.DeviceInfoReportViewBinder;
import com.focusai.efairy.ui.adapter.dev.DeviceInfoViewBinder;
import com.focusai.efairy.ui.adapter.dev.SelectUserToCallAdapter;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.DateUtils;
import com.mylhyl.crlayout.SwipeRefreshRecyclerView;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import me.drakeet.multitype.MultiTypeAdapter;

/**
 * Created by luo_guangwen on 2017/8/7.
 */

public class DeviceDetailInfoActivity extends SwipeBackBaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    public static final String DEVICE_ITEM = "device_item";
    public static final int DEVICE_DRAW_LINE_DATA = 0X10;
    public static final int DEVICE_INFO_DATA = 0X12;
    public static final int DEVICE_CHATTING = 0X11;
    public static final int DEVICE_MAINTAIN = 0X13;
    private DeviceItem deviceItem;
    private SwipeRefreshRecyclerView mRecyclerView;
    private MultiTypeAdapter mAdapter;
    private int[] colors;
    private List<Object> dataList;
    private List<DeviceRealTimeDataItem> realTimeDataItemList;
    public DeviceDetailInfo device_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_device_info);
        initView();
        setDefaultValues();
    }

    @Override
    protected void initView() {
        mRecyclerView = findView(R.id.swipe_recyce_view);
    }

    @Override
    public void initTitte() {
        setCenterTitleName(R.string.dev_info);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_FILTER, 0, R.string.maintain).setIcon(R.drawable.btn_maintain_bg);
        MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);

        MenuItem menuItem = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.control).setIcon(R.drawable.btn_control_selector_);
        MenuItemCompat.setShowAsAction(menuItem, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_FILTER) {
            Intent intent = new Intent(DeviceDetailInfoActivity.this, MaintainRecordeListActivity.class);
            intent.putExtra(MaintainRecordeListActivity.KEY_DEV_ID, deviceItem.efairydevice_id);
            startActivityForResult(intent, DEVICE_MAINTAIN);
        } else if (item.getItemId() == MENU_ITEM_ADD) {
            Intent intent = new Intent(DeviceDetailInfoActivity.this, DevChattingActivity.class);
            intent.putExtra(DevChattingActivity.KEY_DEV_ITEM, deviceItem);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void setDefaultValues() {
        colors = getContext().getResources().getIntArray(R.array.pie_colors);
        deviceItem = (DeviceItem) getIntent().getSerializableExtra(DEVICE_ITEM);
        dataList = new ArrayList<>();
        realTimeDataItemList = new ArrayList<>();
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(DeviceDetailInfo.class, new DeviceInfoViewBinder(getContext()));
        mAdapter.register(DeviceRealTimeDataItem.class, new DeviceInfoCidRealViewBinder(getContext()));
        mAdapter.register(DevLineData.class, new DeviceInfoReportViewBinder(getContext()));
//        mAdapter.register(HelloLineData.class, new DeviceInfoReportViewBinder(getContext()));
        mAdapter.register(ImgAssistInfo.class, new DeviceInfoImgViewBinder(getContext()));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setOnRefreshListener(this);
        mRecyclerView.setEnabledLoad(false);
        mAdapter.setItems(dataList);
        mRecyclerView.setRefreshing(true);
        findView(R.id.btn_call_phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (device_info != null && device_info.efairyproject_user_info_list != null) {
                    openSelecteDialog(device_info.efairyproject_user_info_list);
                }
            }
        });
    }

    @Override
    protected boolean useHandleThread() {
        return true;
    }


    private void loadDeviceDetail(String date, int dayCount) {
        if (deviceItem == null)
            return;
        HttpManager.getInstance().sendRequest(new GetDeviceDetailRequest(deviceItem.efairydevice_id, date, dayCount,
                new Response.Listener<DeviceDetailInfoResponse>() {
                    @Override
                    protected void onSuccess(DeviceDetailInfoResponse response) {
                        if (response != null && response.device_info != null) {
                            device_info = response.device_info;

                            //把项目信息和用户信息合拼一起，如果用户信息有数据则把数据添加到项目信息里面来
                            //1、项目信息为空，用户信息不为空，则创建项目信息list，然后把用户信息添加进来
                            //2、项目信息不为空 用户信息也不为空，则把用户信息数据遍历添加到项目信息list里面
                            //3、都为空错误
                            //4、项目信息不为空，用户信息为空 不操作，因为我们默认使用的数据是项目信息list
                            if(device_info.efairyproject_user_info_list != null && device_info.efairyproject_user_info_list.size() != 0){
                                if(device_info.efairydevice_user_info_list != null && device_info.efairydevice_user_info_list.size() != 0){
                                   for(DeviceDetailInfo.DeviceUserInfo info : device_info.efairydevice_user_info_list){
                                       DeviceDetailInfo.ProjectUserInfo pInfo =  new  DeviceDetailInfo.ProjectUserInfo();
                                       pInfo.efairyuser_id = info.efairyuser_id;
                                       pInfo.efairyuser_nickname = info.efairyuser_nickname;
                                       pInfo.efairyuser_phonenumber = info.efairyuser_phonenumber;
                                       device_info.efairyproject_user_info_list.add(pInfo);
                                   }
                                }
                            }else if(device_info.efairydevice_user_info_list != null && device_info.efairydevice_user_info_list.size() != 0){
                                if(device_info.efairyproject_user_info_list == null){
                                    device_info.efairyproject_user_info_list =  new ArrayList<DeviceDetailInfo.ProjectUserInfo>();
                                }
                                for(DeviceDetailInfo.DeviceUserInfo info : device_info.efairydevice_user_info_list){
                                    DeviceDetailInfo.ProjectUserInfo pInfo =  new  DeviceDetailInfo.ProjectUserInfo();
                                    pInfo.efairyuser_id = info.efairyuser_id;
                                    pInfo.efairyuser_nickname = info.efairyuser_nickname;
                                    pInfo.efairyuser_phonenumber = info.efairyuser_phonenumber;
                                    device_info.efairyproject_user_info_list.add(pInfo);
                                }
                            }


                            if (response.realtime_data != null) {
                                doproceesRealTimeDatas(response.realtime_data.data, response.realtime_data.ts);
                            }
                            getUiHandler().sendEmptyMessage(DEVICE_INFO_DATA);
                            if (response.deviceReltimeDataList != null) {
                                Message msg = getProcHandler().obtainMessage();
                                msg.what = DEVICE_DRAW_LINE_DATA;
                                msg.obj = response.deviceReltimeDataList;
                                getProcHandler().sendMessage(msg);
                            }
                        } else {
                            showToast("设备暂无数据");
                        }
                        mRecyclerView.setRefreshing(false);
                    }

                    @Override
                    protected void onFail(NetworkException exception) {
                        mRecyclerView.setRefreshing(false);
                        doException(exception);
                    }
                }));
    }


    private int  lineChartSize = 0;//有多少个折线图

    public int getLineChartSize(){
        return lineChartSize;
    }


    @Override
    protected boolean procHandlerCallback(Message msg) {
        switch (msg.what) {
            case DEVICE_DRAW_LINE_DATA:
                //这里面是几天的数据
                List<List<DeviceDetailInfoResponse.RealtimeData>> realtimeDataListList = (List<List<DeviceDetailInfoResponse.RealtimeData>>) msg.obj;
                List<DevLineData> devLineDatas = new ArrayList<>();
                if (realtimeDataListList != null && realtimeDataListList.size() > 0) {
                    for (List<DeviceDetailInfoResponse.RealtimeData> realtimeDataList : realtimeDataListList) {
                        LinkedHashMap<Integer, Integer> prhashMap = DeviceDrawHelper.getDrawerableDataPtrCount(realtimeDataList); //需要画多少个拆线图
                        if (prhashMap != null && prhashMap.size() > 0) {
                            for (Map.Entry<Integer, Integer> entry : prhashMap.entrySet()) {
                                devLineDatas.add(DeviceDrawHelper.getDrawerableLineData(getContext(), realtimeDataList, colors, entry.getKey()));
                            }
                        }
                    }
                    Message uimsg = getUiHandler().obtainMessage();
                    uimsg.what = DEVICE_DRAW_LINE_DATA;
                    uimsg.obj = devLineDatas;
                    lineChartSize = devLineDatas.size();//有多少个折线图
                    getUiHandler().sendMessage(uimsg);
                }
                break;
            default:
                break;
        }
        return super.procHandlerCallback(msg);
    }



    @Override
    protected boolean uiHandlerCallback(Message msg) {
        switch (msg.what) {
            case DEVICE_DRAW_LINE_DATA:
                List<DevLineData> entryList = (List<DevLineData>) msg.obj;
                if (entryList != null) {
                    dataList.clear();
                    dataList.add(device_info);
                    if (device_info.efairydevice_imgurl_list != null && device_info.efairydevice_imgurl_list.size() != 0){
                        dataList.add(new ImgAssistInfo(device_info.efairydevice_imgurl_list));
                    }
                    dataList.addAll(realTimeDataItemList);
                    dataList.addAll(entryList);
                    mAdapter.notifyDataSetChanged();
                }
                break;
            case DEVICE_INFO_DATA:
                if (device_info != null) {
                    dataList.add(device_info);
                    if (device_info.efairydevice_imgurl_list != null && device_info.efairydevice_imgurl_list.size() != 0){
                        dataList.add(new ImgAssistInfo(device_info.efairydevice_imgurl_list));
                    }
                    dataList.addAll(realTimeDataItemList);
                    mAdapter.notifyDataSetChanged();
                }
            default:
                break;
        }
        return super.uiHandlerCallback(msg);
    }

    private void doproceesRealTimeDatas(List<DeviceRealTimeDataItem> list, long time) {
        if (list == null)
            return;
        DeviceRealTimeDataItem deviceRealTimeDataItem = null;
        for (DeviceRealTimeDataItem dataItem : list) {
            if (dataItem.cid == 0) {
                deviceRealTimeDataItem = dataItem;
                break;
            }
        }
        realTimeDataItemList.clear();
        if (deviceRealTimeDataItem != null) {
            DeviceRealTimeDataItem newDataItem;
            if (time > 10000) {
                newDataItem = deviceRealTimeDataItem.clone();
                newDataItem.localType = time;
                realTimeDataItemList.add(newDataItem);
            }
            newDataItem = deviceRealTimeDataItem.clone();
            newDataItem.localType = 1;
            realTimeDataItemList.add(newDataItem);

            newDataItem = deviceRealTimeDataItem.clone();
            newDataItem.localType = 2;
            realTimeDataItemList.add(newDataItem);
            list.remove(deviceRealTimeDataItem);
        }
        realTimeDataItemList.addAll(list);
    }

    private void openSelecteDialog(final List<DeviceDetailInfo.ProjectUserInfo> userInfoList) {
        if (userInfoList == null && userInfoList.size() == 0)
            return;
        AlertDialog.Builder builder = new AlertDialog.Builder(DeviceDetailInfoActivity.this);
        SelectUserToCallAdapter locationAdapter = new SelectUserToCallAdapter(getContext(), userInfoList);
        builder.setAdapter(locationAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                DeviceDetailInfo.ProjectUserInfo info = userInfoList.get(which);
                if (info != null) {
                    call(info.efairyuser_phonenumber);
                }
            }
        });
        builder.setTitle("请选择联系人");
        builder.show();
    }

    /**
     * 调用拨号界面
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == DEVICE_CHATTING) {

        }
    }

    @Override
    public void onRefresh() {
        loadDeviceDetail(DateUtils.getCurrentDateStr(), 1);
    }

}
